
import logging
logging.root.setLevel( logging.WARN )
log = logging.getLogger( 'olpcgames.activity' )
log.setLevel( logging.DEBUG )

import pygtk, pygame
from pygame.locals import *
pygtk.require('2.0')
import gtk
import gtk.gdk
import os

from lib.Loader import Loader
from lib.PieceStream import PieceStream
from lib.Board import Board
from lib.Puzzle import PuzzlePieceGroup
from lib.textrect import *
from random import shuffle, choice, randint

from sugar.activity import activity
from sugar.graphics import style
from olpcgames.canvas import PygameCanvas
from olpcgames import mesh, util

__all__ = ['GamePart']

class GamePart(activity.Activity):
    def __init__(self, pieces, orgimg, lecture_name):
        
        self.pieces = pieces
        self.loader = Loader(lecture_name)
        
        self.back = self.loader.load_image("playground.png").convert()
        self.exit_btn = self.loader.load_image("exit.png").convert_alpha()
        self.evaluate_btn = self.loader.load_image("arrow_right.png").convert_alpha()
        self.text_btn = self.loader.load_image("arrow_left.png").convert_alpha()
        
        self.exit_rect = self.exit_btn.get_rect()
        self.evaluate_rect = self.evaluate_btn.get_rect()
        self.text_rect = self.evaluate_btn.get_rect()
                
        self.fnt = self.loader.load_font("FreeSans.ttf", 14)
        self.fntText = self.loader.load_font("FreeSans.ttf", 12)
        self.text = self.loader.load_lecture()        
        
        shuffle(pieces)

        self.stream = PieceStream(pieces)
        self.board  = Board(orgimg, pieces)

        self.floating = []

        self.selected = None
        self.scrolling = False
        self.next_part = 0
        
        self.my_rect = pygame.Rect((110, 150, 450, 250)) 
        self.rendered_text = render_textrect(self.text, self.fntText, self.my_rect, (216, 216, 216), (48, 48, 48), 0, None, None, None)       
        self.text_displayed = 0
        self.eval = 0     
        
        self.drawMainBar()  


    def drawMainBar(self):        
        self.exit_rect.topleft = (610, 10)
        self.evaluate_rect.topleft = (510, 5)
        self.text_rect.topleft = (450, 5)
 
        self.back.blit(self.exit_btn, self.exit_rect.topleft)
        self.back.blit(self.evaluate_btn, self.evaluate_rect.topleft)
        self.back.blit(self.text_btn, self.text_rect.topleft)

 
    def event(self, event):
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                self.next_part = -1
            elif event.key == K_DOWN:
                self.stream.down()
            elif event.key == K_UP:
                self.stream.up()
            elif event.key == K_PAGEDOWN:
                self.stream.down(6)
            elif event.key == K_PAGEUP:
                self.stream.up(6)
        elif event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
                if self.evaluate_rect.collidepoint(event.pos):
                    self.evaluate()
                
                if self.text_rect.collidepoint(event.pos):
                    self.show_text()
                    
                if self.exit_rect.collidepoint(event.pos):
                    self.next_part = -1                    
                    
                self.selected = None
                self.scrolling = False
                if self.stream.is_scroll_hit(event.pos):
                    self.scrolling = True
                else:
                    for p in self.floating[::-1]:
                        if p.is_hit(event.pos):
                            self.selected = p
                            break
                    if self.selected:    
                        self.floating.remove(self.selected)
                        self.floating.append(self.selected)
                        
                    else:
                        self.selected = self.stream.get_piece_at(event.pos)
                        if self.selected:
                            self.stream.remove(self.selected)
                            self.floating.append(self.selected)                                                
            elif event.button == 3:                
                sel = None
                for p in self.floating[::-1]:
                    if p.is_hit(event.pos):
                        if not p.is_piece():
                            sel = p
                            break
                if sel:    
                    self.floating.remove(sel)
                    for p in sel.pieces:
                        p.rect.x+=randint(3, 10)*choice((1, -1))
                        p.rect.y+=randint(3, 10)*choice((1, -1))
                        self.floating.append(p)
            elif event.button == 4:
                self.stream.up()
            elif event.button == 5:
                self.stream.down()
        elif event.type == MOUSEBUTTONUP:            
            if self.scrolling:
                self.scrolling = False
                self.stream.stop_scroll()
            elif self.selected:                    
                if self.board.drop(self.selected):
                    self.floating.remove(self.selected)
                elif self.stream.drop(self.selected):
                    self.floating.remove(self.selected)
                else:
                    friend = None
                    if self.selected.rigth_position():                        
                        print "Position O.K"
                        
                    for f in self.floating:
                        if f == self.selected:
                            continue
                        if f.rigth_position():                        
                            friend = f
                            break
                    
            self.selected = None
        elif event.type == MOUSEMOTION:
            if self.scrolling:
                self.stream.do_scroll(event.pos)
            elif self.selected:
                self.selected.translate(event.rel)

    def update(self, screen):
        screen.blit(self.back, (0, 0))   
        show_background = False
        
        if self.text_displayed == 0 and self.eval == 0:
            self.board.draw(screen)
            self.stream.draw(screen)

            for p in self.floating:
                p.draw(screen)                    
             
        return self.next_part
    
    
    # Evaluates the solution based on the actual position of the floating
    # pieces and their right position  
    def evaluate(self):
        self.back = self.loader.load_image("playground.png").convert()
        self.back.blit(self.exit_btn, self.exit_rect.topleft)
        self.back.blit(self.evaluate_btn, self.evaluate_rect.topleft)
        self.back.blit(self.text_btn, self.text_rect.topleft)         
        
        if self.eval == 1:
            self.eval = 0
            self.text_displayed = 0 
            
        else:                        
            if len(self.pieces) == 0: 
                good = self.loader.load_image("good.png").convert_alpha()                  
                for i in range(len(self.floating)):
                    if self.floating[i].correct == False:                        
                        good = self.loader.load_image("bad.png").convert_alpha()
                        break
            else:
                 good = self.loader.load_image("bad.png").convert_alpha()
                 
            good_rect = good.get_rect()
            good_rect.centerx = self.back.get_rect().centerx    
            good_rect.centery = self.back.get_rect().centery
                
            self.back.blit(good, good_rect)        
            self.eval = 1;     
             
                                   
    # Displays the text of the diagram. Is possible to review the text
    # any time.   
    def show_text(self):
        self.back = self.loader.load_image("playground.png").convert()
        self.back.blit(self.exit_btn, self.exit_rect.topleft)
        self.back.blit(self.evaluate_btn, self.evaluate_rect.topleft)
        self.back.blit(self.text_btn, self.text_rect.topleft)
        
        if self.text_displayed == 1:            
            self.text_displayed = 0
            self.eval = 0

        else:
            txtCanvas = PygameCanvas(200,200)
            
            self.textSurface = pygame.Surface(self.my_rect.size)
            self.back.blit(self.rendered_text, self.my_rect.topleft)
            self.text_displayed = 1
        
        
                 
           
       
   
        
        
        
        